#include "common.h"
#include "log.hpp"

void GetMessage(int fd)
{
    char rbuff[BUFF_SIZE];
    while(true)
    {
        ssize_t sz = read(fd, rbuff, sizeof(rbuff)-1);
        if(sz>0)
        {
            //读取到数据
            rbuff[sz] = 0;
            printf("[%d] clinet say> %s\n", getpid(), rbuff);

        }
        else if(sz == 0)
        {
            //end of file
            printf("[%d] read end of file, clien quit, server quit too!\n", getpid());
            break;
        }
        else
        {
            //read error
            exit(errno);
        }
    }
}

int main()
{
    //1.创建命名管道
    int ret = mkfifo(ipcPath, MODE);
    if(ret == -1) return errno;
    PrintLog("创建命名管道成功！", DEBUG);

    //2.打开管道文件
    int fd = open(ipcPath, O_RDONLY);
    if(ret == -1) return errno;
    PrintLog("打开管道文件成功！", DEBUG);

    //3.进程间通信
    //测试一：
    // char rbuff[BUFF_SIZE];
    // while(true)
    // {
    //     ssize_t sz = read(fd, rbuff, sizeof(rbuff)-1);
    //     if(sz>0)
    //     {
    //         //读取到数据
    //         rbuff[sz] = 0;
    //         printf("[%d] clinet say> %s\n", getpid(), rbuff);

    //     }
    //     else if(sz == 0)
    //     {
    //         //end of file
    //         printf("[%d] read end of file, clien quit, server quit too!\n", getpid());
    //         break;
    //     }
    //     else
    //     {
    //         //read error
    //         exit(errno);
    //     }
    // }
    //测试二：
    int process_num = 3;
    for(int i = 0; i < process_num; ++i)
    {
        pid_t id = fork();
        if(id == -1) exit(errno);
        if(id == 0)
        {
            GetMessage(fd);
            exit(0);
        }
    }
    //等待子进程
    for(int i = 0; i < process_num; ++i)
    {
        pid_t cpid = waitpid(-1, nullptr, 0);
    }

    //4.关闭文件
    close(fd);
    PrintLog("关闭管道文件！", DEBUG);

    //5.删除命名管道
    unlink(ipcPath);
    PrintLog("删除管道文件！", DEBUG);

    return 0;
}